import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class ThreadPoolExecutorTests {
//    队列
    static BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(1);
//    构建线程工厂
    static ThreadFactory threadFactory = new ThreadFactory() {
        private String prefix="pool-thread-task-";
        private AtomicLong atomicLong = new AtomicLong(1);//AtomicLong提供了自增长的
    @Override
    public Thread newThread(Runnable r) {
        return new Thread(r,prefix+atomicLong.getAndIncrement());//incrementAndGet 先递增后取值
    }
};
    public static void main(String[] args) {
        ThreadPoolExecutor tPool =
                new ThreadPoolExecutor(2, 2,
                        3, TimeUnit.SECONDS,workQueue,threadFactory,
                        new ThreadPoolExecutor.CallerRunsPolicy());
        //该线程最大并发为3
        // new ThreadPoolExecutor.CallerRunsPolicy()调用者自己处理的执行策略
//        new ThreadPoolExecutor.AbortPolicy() 调用者拒绝执行策略
//        new ThreadPoolExecutor.DiscardPolicy() 丢弃没有执行的任务
//        new ThreadPoolExecutor.DiscardOldestPolicy() 丢弃最先开始的任务
        tPool.execute(new Runnable() {
            @Override
            public void run() {
                String task =  Thread.currentThread().getName()+"->task-1";
                System.out.println(task);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        tPool.execute(new Runnable() {
            @Override
            public void run() {
               String task =  Thread.currentThread().getName()+"->task-2";
                System.out.println(task);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        tPool.execute(new Runnable() {
            @Override
            public void run() {
                String task =  Thread.currentThread().getName()+"->task-3";
                System.out.println(task);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        tPool.execute(new Runnable() {
            @Override
            public void run() {
                String task =  Thread.currentThread().getName()+"->task-4";
                System.out.println(task);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
